package com.ruoyi.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.db.domain.ProductInfo;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.product.constant.ProductConstant;
import com.ruoyi.product.enums.ProdTypeEnum;
import com.ruoyi.product.service.IProductInfoService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService implements IProductService {

    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IProductInfoService productInfoService;

    @Override
    public AjaxResult addProductInfo(ProductInfo productInfo){

        // 判断产品类型，是否需要
//        if (StrUtil.equals(String.valueOf(productInfo.getType()), String.valueOf(ProdTypeEnum.QIWEI.getValue()))){
//            //
//            AjaxResult ajaxResult = this.initQiVProdUserInfo(productInfo);
//            Integer codeType = (Integer) ajaxResult.get(AjaxResult.CODE_TAG);
//            if (ObjectUtil.equals(codeType, AjaxResult.Type.ERROR)){
//                return ajaxResult;
//            }
//        }

        int i = productInfoService.insertProductInfo(productInfo);

        return i>0?AjaxResult.success():AjaxResult.error();
    }


    public AjaxResult initQiVProdUserInfo(ProductInfo productInfo){

        String numbers = RandomUtil.randomNumbers(8);
        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(productInfo.getProductName());
        sysUser.setLoginName(numbers);

        String password = RandomUtil.randomString(6);
        sysUser.setPassword(password);
        sysUser.setSalt(ShiroUtils.randomSalt());
        sysUser.setPassword(passwordService.encryptPassword(sysUser.getLoginName(), sysUser.getPassword(), sysUser.getSalt()));
        sysUser.setCreateBy("system");

        sysUser.setDeptId(Long.valueOf(ProductConstant.PRODUCT_TYPE_QIWEI_DEPT_ID));
        sysUser.setRoleIds(new Long[]{Long.valueOf(ProductConstant.PRODUCT_TYPE_QIWEI_ROLE_ID)});
        int i = sysUserService.insertUser(sysUser);
        if (i<1){
            return AjaxResult.error("生成管理员账户失败");
        }
        productInfo.setUserId(sysUser.getUserId());
        productInfo.setUserName(numbers);
        productInfo.setUserPwd(password);
        return AjaxResult.success();
    }
}
